<?php
	session_start();
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Service/UserService.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Service/AuthenticationService.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/Context/BaseContext.php';
    require_once dirname(__FILE__).DIRECTORY_SEPARATOR.'../model/ServiceResult/ServiceResult.php';
    $userService = new UserService();   
	$context = new BaseContext();
	$result = new ServiceResult();
    $success = true;
    
    $newPass = $_POST['newPass'];
    $confirmPass = $_POST['confirmNewPass'];
    $token = $_POST['token'];
    if($newPass == '')
    {
    	echo "Please Enter New Password";
    	$success = false;
    }
    if($confirmPass != $newPass)
    {
   		echo "Passwords Do Not Match!"; 	
   		$success = false;
    }
    if($success == true)
    {
    	$user = $userService->getUserByToken($context, $result, $token);
    	$ID = $user['ID'];
    	$data['pass'] = Tool::md5_base64($newPass);
    	$data['eToken'] = null;
    	$data['ID'] = $ID;
    	$userDomain = new UserDomain($data);
    	$userService->resetPass($context, $result, $userDomain);
    	$uname = $user['uname'];
    	$authenticationService = new AuthenticationService();	
    	$loginResult = $authenticationService->login($context, $result, $uname, $newPass);
    	if($loginResult != false)
		{
			$_SESSION['user']['ID'] = $loginResult->getID();
			$_SESSION['user']['username'] = $loginResult->getUname();
			$_SESSION['user']['type'] = $loginResult->getType();
			$_SESSION['user']['lastLogin'] = $loginResult->getLastLogin();
			$dateTime = date('Y-m-d h:i:s', time());
			$loginResult->setLastLogin($dateTime);
			$authenticationService->update($context, $result, $loginResult);
			echo "<script>window.location.replace('index.php?func=dash');</script>";
		}
    }
?>